import {
  Controller,
  Post,
  Get,
  Delete,
  Param,
  UseGuards,
  Request,
  UseInterceptors,
  UploadedFile,
  Res,
  Body,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { Response } from 'express';
import { UploadService } from './upload.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';

@Controller('upload')
export class UploadController {
  constructor(private uploadService: UploadService) {}

  @Post()
  @UseGuards(JwtAuthGuard)
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(
    @UploadedFile() file: Express.Multer.File,
    @Request() req,
    @Body() body: { fileName: string },
  ) {
    return this.uploadService.uploadFile(file, req.user.id, body.fileName);
  }

  @Get(':id')
  @UseGuards(JwtAuthGuard)
  async getFile(@Param('id') id: string, @Request() req, @Res() res: Response) {
    const { file, filePath } = await this.uploadService.getFile(
      parseInt(id),
      req.user.id,
    );

    res.setHeader('Content-Type', file.mimeType || 'application/octet-stream');
    // 编码文件名
    const encodedFilename = encodeURIComponent(file.name);
    res.setHeader(
      'Content-Disposition',
      `inline; filename="${encodedFilename}"`,
    );

    const fs = require('fs');
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
  }

  @Get('file/:filename')
  async getFileByFilename(
    @Param('filename') filename: string,
    @Res() res: Response,
  ) {
    const { file, filePath } =
      await this.uploadService.getFileByFilename(filename);
    res.setHeader('Content-Type', file.mimeType || 'application/octet-stream');
    // 编码文件名
    const encodedFilename = encodeURIComponent(file.name);
    res.setHeader(
      'Content-Disposition',
      `inline; filename="${encodedFilename}"`,
    );
    const fs = require('fs');
    const fileStream = fs.createReadStream(filePath);
    fileStream.pipe(res);
  }

  @Delete(':id')
  @UseGuards(JwtAuthGuard)
  async deleteFile(@Param('id') id: string, @Request() req) {
    return this.uploadService.deleteFile(parseInt(id), req.user.id);
  }
}
